package control;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import model.Divisi;
import model.Pegawai;

public class LoginKontrol {

    private Connection conn;

    public LoginKontrol(Connection koneksi) {
        this.conn = koneksi;
    }

     public static LoginKontrol getKoneksiKategori() throws SQLException {
        LoginKontrol kon;
        kon = new LoginKontrol(OraConnection.getKoneksi());
        return kon;
    }
    public static LoginKontrol login(String user, String pwd, String url) throws SQLException {

        LoginKontrol kon = new LoginKontrol(OraConnection.open(user, pwd, url));
        return kon;

    }

    public void login(Pegawai peg) throws SQLException {
        Statement statement = null;
        ResultSet result = null;
        System.out.println(peg.getDivisi().getIdDivisi());
        System.out.println(peg.getUsername());
        System.out.println(peg.getPassword());
        try {
            statement = conn.createStatement();
            String sql = "SELECT pegawai.namapegawai, "
                    + "divisi.namadivisi, divisi.iddivisi "
                    + "FROM pegawai,divisi "
                    + "where pegawai.divisi=divisi.iddivisi and "
                    + "pegawai.username='" + peg.getUsername() + "' and pegawai.password ='" + peg.getPassword() + "' "
                    + "and divisi.iddivisi='" + peg.getDivisi().getIdDivisi() + "'";
            result = statement.executeQuery(sql);
            List<Pegawai> pegawai = new ArrayList<Pegawai>();
            
            while (result.next()) {
                Divisi div = new Divisi();
                div.setNamaDivisi(result.getString("namadivisi"));
                div.setIdDivisi(result.getString("iddivisi"));
                System.out.println(div.getNamaDivisi());
//                if(div.getNamaDivisi()==null && peg.getUsername(). == null && peg.getPassword() == null){
//                    JOptionPane.showMessageDialog(null,"Username&password salah ");
//                    break;
//                }
                peg.setNamaPegawai(result.getString("namapegawai"));
                peg.setDivisi(div);
                pegawai.add(peg);
            }
            conn.close();
        } catch (SQLException ex) {
            Logger.getLogger(LoginKontrol.class.getName()).log(Level.SEVERE, null, ex);

        }
    }
}
